package richbar.com.richbar.fragment.product;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.common.base.BaseActivity;
import com.common.base.BaseFragment;
import com.common.help.RecycleViewHelp;
import com.common.util.LogUtil;
import com.common.util.StringUtil;
import com.common.util.ToastUtil;
import com.okhttp.GlideUtil;
import com.okhttp.network.HttpUtils;
import com.okhttp.network.MyGson;
import com.smarttop.library.bean.City;
import com.smarttop.library.bean.County;
import com.smarttop.library.bean.Province;
import com.smarttop.library.bean.Street;
import com.smarttop.library.widget.AddressSelector;
import com.smarttop.library.widget.BottomDialog;
import com.smarttop.library.widget.OnAddressSelectedListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import richbar.com.richbar.R;
import richbar.com.richbar.activity.product.FirmOrderAc;
import richbar.com.richbar.activity.product.ProductDetailsAc;
import richbar.com.richbar.base.BaseApplication;
import richbar.com.richbar.base.BaseListAdapter;
import richbar.com.richbar.base.S;
import richbar.com.richbar.bean.AddCarResult;
import richbar.com.richbar.bean.AddressResult;
import richbar.com.richbar.bean.CollectDelResult;
import richbar.com.richbar.bean.CollectResult;
import richbar.com.richbar.bean.CommentResult;
import richbar.com.richbar.bean.GoodsInfoResult;
import richbar.com.richbar.bean.SetAddressResult;
import richbar.com.richbar.fragment.ShoppingCartFragment;
import richbar.com.richbar.util.LoadingDialog;
import richbar.com.richbar.util.NetWorkUtil;
import richbar.com.richbar.util.Util;
import richbar.com.richbar.view.BannerLayout;
import richbar.com.richbar.view.ItemWebView;
import richbar.com.richbar.view.NoScrollGridView;
import richbar.com.richbar.view.pop.SelectAddressPop;
import richbar.com.richbar.view.pop.TypePop;
import richbar.com.richbar.view.product.SlideDetailsLayout;

/**
 * Created by QiYang on 2018/11/27.
 */

public class ProductInfoFragment extends BaseFragment {
    private Callback callback;
    public static ProductInfoFragment newInstance(String id,String pic){
        ProductInfoFragment fragment = new ProductInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id",id);
        bundle.putString("pic",pic);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @BindView(R.id.heart)
    ImageView heart;
    @BindView(R.id.star)
    ImageView star;
    @BindView(R.id.vp_item_goods_img)
    BannerLayout vp_item_goods_img;
    @BindView(R.id.sv_switch)
    SlideDetailsLayout sv_switch;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.proce_point)
    TextView procePoint;
    @BindView(R.id.rebate)
    TextView rebate;
    @BindView(R.id.rebate_point)
    TextView rebatePoint;
    @BindView(R.id.shop)
    TextView shop;
    @BindView(R.id.select_status)
    TextView selectStatus;
    @BindView(R.id.select)
    TextView select;
    @BindView(R.id.delivery_range)
    TextView deliveryRange;
    @BindView(R.id.delivery_status)
    TextView deliveryStatus;
    @BindView(R.id.comment_head1)
    ImageView commentHead1;
    @BindView(R.id.comment_nickname1)
    TextView commentNickname1;
    @BindView(R.id.comment1)
    TextView comment1;
    @BindView(R.id.recycleView1)
    RecyclerView recycleView1;
    @BindView(R.id.type1)
    TextView type1;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.comment_head2)
    ImageView commentHead2;
    @BindView(R.id.comment_nickname2)
    TextView commentNickname2;
    @BindView(R.id.comment2)
    TextView comment2;
    @BindView(R.id.recycleView2)
    RecyclerView recycleView2;
    @BindView(R.id.type2)
    TextView type2;
    @BindView(R.id.comment_num)
    TextView comment_num;
    @BindView(R.id.webView)
    ItemWebView webView;
    @BindView(R.id.recycleView_comment)
    RecyclerView recycleView_comment;
    @BindView(R.id.body)
    LinearLayout body;
    Unbinder unbinder;
    private GoodsInfoResult.DataEntity.InfoEntity bean;
    private WebSettings webSettings;
    private ProductDetailsAc ac;
    private AddressResult.AddressBean addressBean;
    private boolean isStar;
    private boolean isHeart;
    private String goods_collect_id;
    private String seller_collect_id;
    private LoadingDialog loadingDialog;
    private MyAdapter adapter;//评论
    private BottomDialog dialog;
    private Province province;
    private City city;
    private County county;
    private Street street;
    List<String> ids = new ArrayList<>();
    List<String> values = new ArrayList<>();
    private String pic;


    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_product_info, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        ac= (ProductDetailsAc) context;
    }

    @Override
    protected void initData() {
        loadingDialog = new LoadingDialog(getActivity(),0);
        String id = getArguments().getString("id");
        pic = getArguments().getString("pic");
        sv_switch.setOnSlideDetailsListener(new SlideDetailsLayout.OnSlideDetailsListener() {
            @Override
            public void onStatucChanged(SlideDetailsLayout.Status status) {
                if (status == SlideDetailsLayout.Status.OPEN){
                    //图文详情
                    ac.tv_title.setVisibility(View.VISIBLE);
                    ac.psts_tabs.setVisibility(View.GONE);
                }else {
                    ac.tv_title.setVisibility(View.GONE);
                    ac.psts_tabs.setVisibility(View.VISIBLE);
                }
            }
        });
        getData(id);
        getComment();
    }

    private void getComment() {
        adapter = new MyAdapter(R.layout.item_product_comment,new ArrayList<CommentResult.DataEntity.RowsEntity>());
        RecycleViewHelp.setManager(recycleView_comment,getActivity());
        recycleView_comment.setAdapter(adapter);
        NetWorkUtil.getRateList(currentPage(), "6", ac.getGoodsId(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                final CommentResult result = MyGson.getInstance().fromJson(data, CommentResult.class);
                if (checkIsOk(result)){
                    setComment(result);
                }
            }
        });
    }

    private void setComment(CommentResult result) {
        comment_num.setText("评价(" + result.getData().getTotal() + ")");
        adapter.setNewData(result.getData().getRows());
    }

    private void getData(String id) {
        NetWorkUtil.goodsInfo(id, Util.md5(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                final GoodsInfoResult result = MyGson.getInstance().fromJson(data, GoodsInfoResult.class);
                setData(result);
                callback.callback(result.getData().getInfo());
            }
        });
    }

    private void setData(GoodsInfoResult result) {
        bean = result.getData().getInfo();
        name.setText(bean.getGoods_name());
        String goodsPrice = bean.getGoods_price();
        if (!StringUtil.isEmpty(goodsPrice)) {
            price.setText(goodsPrice.substring(0, goodsPrice.indexOf(".")));
            procePoint.setText(goodsPrice.substring(goodsPrice.indexOf("."), goodsPrice.length()));
        }
        String goodsRebate = bean.getGoods_rebate();
        if (!StringUtil.isEmpty(goodsRebate)) {
            rebate.setText(goodsRebate.substring(0, goodsRebate.indexOf(".")));
            rebatePoint.setText(goodsRebate.substring(goodsRebate.indexOf("."), goodsRebate.length()));
        }
        shop.setText(bean.getGoods_sellername());
        comment_num.setText("评价(" + bean.getGoods_rate() + ")");

        switch (bean.getGoods_promotion()){
            case "0":
                num.setText("暂无优惠");
                break;
            case "1":
                num.setText("最多可以使用" + bean.getGoods_promotion_num() + "张蚂蚁券") ;
                break;
            case "2":
                num.setText("最多可以使用" + bean.getGoods_promotion_num() + "蚂蚁豆") ;
                break;
        }

        isHeart = bean.getIs_collect_goods() == 1 ? false : true;
        isStar = bean.getIs_collect_seller() == 1 ? false : true;

        LogUtil.e("PPPPPPPPP",bean.getIs_collect_goods());

        if (isHeart){
            heart.setBackgroundResource(R.mipmap.heart_red);
        }else {
            heart.setBackgroundResource(R.mipmap.heart_black);
        }
        if (isStar){
            star.setBackgroundResource(R.mipmap.like_red);
        }else {
            star.setBackgroundResource(R.mipmap.like_black);
        }

        goods_collect_id = bean.getGoods_collid();
        seller_collect_id = bean.getSeller_collid();

        deliveryRange.setText(bean.getAddress());


        if (null != bean && null != bean.getAttr() && bean.getAttr().size() > 0) {


            for (int i = 0; i < bean.getAttr().size(); i++) {
                ids.add(bean.getAttr().get(i).getValue().get(0).getId() + "");
                values.add(bean.getAttr().get(i).getValue().get(0).getName());
            }
        }
        select.setText(StringUtil.listToStr(values));
        callback.attrs(false,StringUtil.listToStr(ids),StringUtil.listToStr(values),bean.getGoods_price(),"1");

        setBanner(bean);

        getWebView();
    }

    private void setBanner(GoodsInfoResult.DataEntity.InfoEntity bean) {
        List<GoodsInfoResult.DataEntity.InfoEntity.GoodsImgEntity> data = bean.getGoods_img();
        if (data == null || data.size() == 0){
            return;
        }
        String s = data.get(0).getImg();
        String[] arr = s.split(","); // 用,分割
        List<String> urls = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            urls.add(NetWorkUtil.URL + arr[i]);
        }
        vp_item_goods_img.setViewUrls(urls);
        vp_item_goods_img.setOnBannerChangeListener(new BannerLayout.OnBannerChangeListener() {
            @Override
            public void onChange(int position) {

            }
        });
        vp_item_goods_img.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }
        });
    }

    @OnClick({R.id.star,R.id.heart,R.id.select_body, R.id.delivery_body, R.id.look_all_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.heart:
                if (!isHeart){
                    collect("1",bean.getGoods_id()+"");
                }else {
                    unCollect("1",goods_collect_id);
                }
                break;
            case R.id.star:
                if (!isStar){
                    collect("2",bean.getGoods_sellerid()+"");
                }else {
                    unCollect("2",seller_collect_id);
                }
                break;
            case R.id.select_body://规格尺寸
                LogUtil.e("FFFFFFFFF","222");
                showType();
                break;
            case R.id.delivery_body://地址
                LogUtil.e("FFFFFFFFF","111");
                showAddress();
                break;
            case R.id.look_all_comment:
                LogUtil.e("FFFFFFFFF","333");
                ac.setViewPagerPosition(2);
                break;
        }
    }

    private void showType() {
        TypePop pop = new TypePop(getActivity(), pic,bean);
        pop.show(new TypePop.Callback() {
            @Override
            public void onBuy(final String id, final String value, final String price, final String num) {
                LogUtil.e("ADADDADAD",id);
                callback.attrs(true,id,value,price,num);
                start(FirmOrderAc.class, new BaseActivity.OnBundleListener() {
                    @Override
                    public Bundle onSetBundle(Bundle bundle) {
                        bundle.putString("id", bean.getGoods_id()+"");
                        bundle.putString("ids", id);
                        bundle.putString("price", price);
                        bundle.putString("num", num);
                        bundle.putString("values", value);
                        return bundle;
                    }
                });
            }

            @Override
            public void onAdd(String id, String values, String price, String num) {
                addCar(id,values,price,num);
                LogUtil.e("ADADDADAD",id);
            }
        });
    }

    private void addCar(String id, final String values, String price, String num) {
        NetWorkUtil.addCart(BaseApplication.uid, bean.getGoods_id() + "", num,price,id, Util.md5(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                select.setText(values);
                final AddCarResult result = MyGson.getInstance().fromJson(data, AddCarResult.class);
                if (checkIsOk(result)){
                    if (!StringUtil.isEmpty(result.getData().getCart_id())){
                        ToastUtil.showToast(getActivity(),"添加成功");
                        ShoppingCartFragment.sendBraodcast(getActivity());
                    }else {
                        ToastUtil.showToast(getActivity(),"添加失败");
                    }
                }
            }
        });
    }


    private void showAddress() {
        //loadingDialog.show();
        Log.d("AAAAAAAAA","111");
        SelectAddressPop pop = new SelectAddressPop(getActivity());
        pop.show(body, new SelectAddressPop.Callback() {
            @Override
            public void onAddressId(AddressResult.AddressBean bean) {
                loadingDialog.dismiss();
                addressBean = bean;
                deliveryRange.setText(bean.getAddress());
                NetWorkUtil.setAddress(bean.getId(), new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        loadingDialog.dismiss();
                        final SetAddressResult result = MyGson.getInstance().fromJson(data, SetAddressResult.class);
                    }
                });
            }

            @Override
            public void onSelectOtherAddress() {
                selectOtherAddress();
            }
        });
    }

    private void selectOtherAddress() {
        dialog = new BottomDialog(getActivity());
        dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                ProductInfoFragment.this.province = province;
                ProductInfoFragment.this.city = city;
                ProductInfoFragment.this.county = county;
                ProductInfoFragment.this.street = street;
                deliveryRange.setText((null == province ? "":province.name) +
                        (null == city ? "" : city.name) +
                        (null == county ? "" : county.name) +
                        (null == street ? "":street.name));
                if (dialog != null){
                    dialog.dismiss();
                }
            }
        });
        dialog.setDialogDismisListener(new AddressSelector.OnDialogCloseListener() {
            @Override
            public void dialogclose() {
                if (dialog != null){
                    dialog.dismiss();
                }
            }
        });
        dialog.show();
    }


    /**
     * 收藏
     * @param type
     * @param id
     */
    private void collect(final String type, String id) {
        loadingDialog.show();
        NetWorkUtil.addCollect(BaseApplication.uid, type, id, Util.md5(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                final CollectResult result = MyGson.getInstance().fromJson(data, CollectResult.class);
                if (checkIsOk(result)){
                    loadingDialog.dismiss();
                    if (Integer.valueOf(result.getData().getColl_id()) > 0){
                        ToastUtil.showToast(getActivity(),"收藏成功");
                        switch (type){
                            case "1":
                                isHeart = true;
                                heart.setBackgroundResource(R.mipmap.heart_red);
                                goods_collect_id = result.getData().getColl_id();
                                break;
                            case "2":
                                isStar = true;
                                star.setBackgroundResource(R.mipmap.like_red);
                                seller_collect_id = result.getData().getColl_id();
                                break;
                        }
                    }else {
                        ToastUtil.showToast(getActivity(),"收藏失败");
                    }
                }
            }
        });
    }

    private void unCollect(final String type, String collectId){
        loadingDialog.show();
        NetWorkUtil.delCollect(type,collectId, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                final CollectDelResult result = MyGson.getInstance().fromJson(data, CollectDelResult.class);
                if (checkIsOk(result)){
                    loadingDialog.dismiss();
                    if (result.getData().getResult() == 1){
                        ToastUtil.showToast(getActivity(),"删除成功");
                        switch (type){
                            case "1":
                                isHeart = false;
                                heart.setBackgroundResource(R.mipmap.heart_black);
                                break;
                            case "2":
                                isStar = false;
                                star.setBackgroundResource(R.mipmap.like_black);
                                break;
                        }
                    }else {
                        ToastUtil.showToast(getActivity(),"删除失败");
                    }
                }
            }
        });
    }


    private void getWebView(){
        String id = getArguments().getString("id");
        String url = NetWorkUtil.URL + "/home/goods/detail?gid=" + id;
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //设置自适应屏幕
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小


        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        // 设置可以支持缩放
        webSettings.setSupportZoom(true);

        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);

        LogUtil.e("ETTWETWETW",url);
        webView.loadUrl(url);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }





    class MyAdapter extends BaseQuickAdapter<CommentResult.DataEntity.RowsEntity> {
        public MyAdapter(int layoutResId, List<CommentResult.DataEntity.RowsEntity> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder holder, CommentResult.DataEntity.RowsEntity bean) {
            holder.setText(R.id.comment_nickname1,bean.getNickname());
            ImageView head = holder.getView(R.id.comment_head1);
            GlideUtil.loadImage(getActivity(),NetWorkUtil.URL + bean.getHead(),head);
            holder.setText(R.id.comment1,bean.getContent());
            holder.setText(R.id.type1,bean.getAttr());
            NoScrollGridView gridView = holder.getView(R.id.gridView);
            GridAdapter adapter = new GridAdapter(getActivity(),bean.getImg());
            gridView.setAdapter(adapter);
        }
    }

    class GridAdapter extends BaseListAdapter<CommentResult.DataEntity.RowsEntity.ImgEntity> {
        public GridAdapter(Context context, List<CommentResult.DataEntity.RowsEntity.ImgEntity> data) {
            super(context, data);
        }

        @Override
        public View convert(int i, View view, ViewGroup viewGroup, CommentResult.DataEntity.RowsEntity.ImgEntity bean) {
            View v = LayoutInflater.from(getActivity()).inflate(R.layout.item_pic,null);
            ImageView pic = v.findViewById(R.id.item_pic);
            GlideUtil.loadImage(context,NetWorkUtil.URL + bean.getImgpath(),pic);
            return v;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public interface Callback{
        void callback(GoodsInfoResult.DataEntity.InfoEntity bean);
        void attrs(boolean isSelect, String ids, String values, String price, String num);
    }

}
